<template>
  <div>
    <div class="card px-3 pt-3 mb-3">
      <el-form @submit.native.prevent :inline="true">
        <el-form-item>
          <el-date-picker
            v-model="formData.dateRange"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            unlink-panels
            @change="handleQuery"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <select-address
            v-model="queryParams.addressCode"
            placeholder="地址查询"
            auto-top
            clearable
            :bottom-level="2"
            @change="handleQuery"
          ></select-address>
        </el-form-item>
        <!-- <el-form-item>
        <select-org-bank v-model="formData.bankId"
                         placeholder="选择银行"
                         filterable
                         clearable
                         @select="selectBank"></select-org-bank>
      </el-form-item> -->
        <el-form-item>
          <c-select
            style="width: 140px"
            :options="enumBusType"
            number-key
            clearable
            placeholder="业务模式"
            v-model="formData.busType"
            @change="handleQuery"
          ></c-select>
        </el-form-item>
        <el-form-item>
          <select-main-business
            clearable
            placeholder="十二大产业分类"
            v-model="formData.mainBus"
            @change="handleSelectMainBus"
          ></select-main-business>
        </el-form-item>
        <!-- <el-form-item> -->
        <!-- <c-select :options="enumKeyAreaType"
                  clearable
                  placeholder="选择区域类型"
                  v-model="formData.areaType"
                  @change="handleQuery"></c-select> -->

        <!-- <c-select
            :options="{ 0: '否', 1: '是' }"
            v-model="formData.is93"
            clearable
            placeholder="是否9+3大县"
            @change="handleQuery"
          ></c-select> -->
        <!-- </el-form-item> -->
        <!-- <el-form-item>
        <el-date-picker v-model="formData.createTime"
                        type="month"
                        placeholder="导入时间"
                        @change="handleQuery">
        </el-date-picker>
      </el-form-item> -->
        <el-form-item>
          <el-button :loading="loading" icon="el-icon-search" @click="listGetData()">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="card p-3 mb-3">
      <div class="analy-title">产业统计分析</div>
      <div class="w-100">
        <el-echarts
          theme="macarons"
          :loading="loading"
          :height="300"
          :option="chartOption"
        ></el-echarts>
      </div>
    </div>

    <div class="card p-3">
      <div class="d-flex justify-content-between mb-3">
        <div class="analy-title">项目详情数据</div>

        <div class="d-flex">
          <el-radio-group class="anylay-type-radio mr-3" v-model="projectType">
            <el-radio-button
              v-for="(type, index) in enumProjectType"
              :key="index"
              :label="type.value"
            >
              <span class="mx-3">{{ type.label }}</span>
              <!-- <span>{{type.count}}</span> -->
            </el-radio-button>
          </el-radio-group>
          <el-button
            :loading="downloadLoading"
            type="text"
            icon="el-icon-download"
            @click="exportExcel()"
          >
            下载{{ projectTypeLabel }}项目
          </el-button>
        </div>
      </div>

      <div v-show="projectType === 0">
        <analy-list ref="listRef0" :query-params="inQueryParams"></analy-list>
      </div>
      <div v-show="projectType === 1">
        <analy-list ref="listRef1" :query-params="outQueryParams"></analy-list>
      </div>
      <div v-show="projectType === 2">
        <analy-list ref="listRef2" :query-params="newQueryParams"></analy-list>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getMonthLastDayDate } from '@/common/plugins/tools/date'

import { enumMainBusiness } from '@/credit/plugins/enum'
import { echartsXFormatter } from '@vimi/utils-tool'
import { enumBusType, enumProjectType, getParams } from './reportMixins'

import SelectAddress from '@/components/select/SelectAddress'
// import SelectOrgBank from '@/bigcredit/views/program/components/SelectOrgBank'
import SelectMainBusiness from '@/credit/components/select/SelectMainBusiness'
import AnalyList from '@/credit/views/city/report/AnalyList'

export default {
  components: {
    SelectAddress,
    // SelectOrgBank,
    AnalyList,
    SelectMainBusiness,
  },
  props: {},
  data() {
    return {
      enumBusType,
      loading: false,
      downloadLoading: false,
      formData: {
        dateRange: [],
        bankId: '',
        busType: '',
        mainBus: '',
      },
      queryParams: {
        clientId: '',
        addressCode: '',
        startDate: '',
        endDate: '',
        bankCode: '',
        busStatus: '',
        guaType: '1,2,3,4',
        mainBus: '',
      },

      chartOption: {},

      enumProjectType,
      projectType: 0,
    }
  },
  computed: {
    ...mapGetters(['clientId']),
    projectTypeLabel() {
      const item = enumProjectType.find(it => it.value === this.projectType)
      return item ? item.label : ''
    },
    inQueryParams() {
      return {
        ...this.queryParams,
        busStatus: 0,
      }
    },
    outQueryParams() {
      return {
        ...this.queryParams,
        busStatus: 1,
      }
    },
    newQueryParams() {
      return {
        ...this.queryParams,
        busStatus: 2,
      }
    },
  },
  watch: {},
  created() {
    this.setDateParams()
    this.getData()
  },
  mounted() {},
  methods: {
    setDateParams() {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth()

      let startYear = year - 1
      let startMonth = month + 1
      if (startMonth === 12) {
        startYear++
        startMonth = 0
      }
      const start = new Date(startYear, startMonth, 1)
      const end = getMonthLastDayDate(year, month)

      this.formData.dateRange = [start, end]
      this.queryParams.startDate = start
      this.queryParams.endDate = end
      this.queryParams.clientId = this.clientId
    },
    getCountData(partParams) {
      const tableName = 'market_project'
      const { mainBus, ...addParams } = { ...partParams }
      const params = getParams({
        isBIQuery: 1,
        groupFields: 'main_business',
        fields: ['main_business'],
        groupFunc: 'count(customer_related_id),round(sum(warranty_amount)|2)',
        clientId: this.clientId,
        ...addParams,
      })
      return this.$api.getData(this.$serviceName, tableName, params)
    },
    async getData() {
      this.loading = true
      const xData = []
      Object.keys(enumMainBusiness).forEach(key => {
        xData.push(enumMainBusiness[key])
      })
      // 在保
      const aData = []
      const bData = []
      // 解保
      const cData = []
      const dData = []
      // 新增
      const eData = []
      const fData = []

      Promise.all([
        this.getCountData(this.inQueryParams),
        this.getCountData(this.outQueryParams),
        this.getCountData(this.newQueryParams),
      ])
        .then(([inData, unData, newData]) => {
          const inObject = this.getObjectData(inData.data || [])
          const unObject = this.getObjectData(unData.data || [])
          const newObject = this.getObjectData(newData.data || [])
          xData.forEach(item => {
            aData.push((inObject[item] || {}).total || '')
            bData.push((inObject[item] || {}).funds || '')
            cData.push((unObject[item] || {}).total || '')
            dData.push((unObject[item] || {}).funds || '')
            eData.push((newObject[item] || {}).total || '')
            fData.push((newObject[item] || {}).funds || '')
          })
        })
        .finally(() => {
          this.setOption({
            xData,
            aData,
            bData,
            cData,
            dData,
            eData,
            fData,
          })
          this.loading = false
        })
    },
    getObjectData(data) {
      const obj = {}
      data.forEach(item => {
        obj[item.main_business] = {
          total: item.p,
          funds: item.p1,
        }
      })
      return obj
    },
    listGetData() {
      this.getData()
      const { listRef0, listRef1, listRef2 } = this.$refs
      listRef0 && listRef0.getData()
      listRef1 && listRef1.getData()
      listRef2 && listRef2.getData()
    },

    exportExcel() {
      const listRef = this.$refs[`listRef${this.projectType}`]
      if (listRef) {
        this.downloadLoading = true
        listRef.exportExcel(`${this.projectTypeLabel}项目`).finally(() => {
          this.downloadLoading = false
        })
      }
    },

    handleQuery() {
      const { dateRange, busType, is93 } = this.formData
      // this.queryParams.createTime = createTime
      // 时间处理
      if (!dateRange) {
        this.setDateParams()
      } else {
        this.queryParams.startDate = dateRange[0]
        this.queryParams.endDate = getMonthLastDayDate(
          dateRange[1].getFullYear(),
          dateRange[1].getMonth()
        )
      }

      // 业务类型
      this.queryParams.guaType = busType === 1 ? '4' : busType === 0 ? '1,2,3' : '1,2,3,4'
      this.queryParams['is_9_3.eq'] = is93
      this.getData()
    },
    selectBank(bank) {
      this.queryParams.bankCode = bank.agency_code || ''
      this.getData()
    },
    handleSelectMainBus() {
      this.queryParams.mainBus = this.formData.mainBus
      // this.getData()
    },

    setOption(data) {
      this.chartOption = {
        title: {
          text: '',
          subtext: '',
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['在保项目', '解保项目', '新增项目', '在保金额', '解保金额', '新增金额'],
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        grid: {
          top: 80,
          left: 100,
          right: 100,
          bottom: 80,
        },
        xAxis: [
          {
            type: 'category',
            data: data.xData,
            axisLabel: {
              formatter: v => echartsXFormatter(v, 4),
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '项目数（个）',
          },
          {
            type: 'value',
            name: '金额（万元）',
          },
        ],
        series: [
          {
            name: '在保项目',
            type: 'bar',
            yAxisIndex: 0,
            data: data.aData,
            label: { show: true, position: 'top' },
          },
          {
            name: '解保项目',
            type: 'bar',
            yAxisIndex: 0,
            data: data.cData,
            label: { show: true, position: 'top' },
          },
          {
            name: '新增项目',
            type: 'bar',
            yAxisIndex: 0,
            data: data.eData,
            label: { show: true, position: 'top' },
          },
          {
            name: '在保金额',
            type: 'line',
            yAxisIndex: 1,
            data: data.bData,
            label: { show: false, position: 'inside' },
          },
          {
            name: '解保金额',
            type: 'line',
            yAxisIndex: 1,
            data: data.dData,
            label: { show: false, position: 'inside' },
          },
          {
            name: '新增金额',
            type: 'line',
            yAxisIndex: 1,
            data: data.fData,
            label: { show: false, position: 'inside' },
          },
        ],
      }
    },
  },
}
</script>

<style lang="scss" scoped>
@import './analy.scss';
</style>
